<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { getSceneListByDeviceGroupApi, setDeviceGroupSceneRelApi } from '@/api/alerts/alertOperate';
import { useLogic } from "@/views/system/user/logic/logic";
import { getAlertSceneOptionsApi } from "@/api/alerts/alertScene";

const props = defineProps(
  {
    visible: {
      require: false,
      type: Boolean,
      default: false
    },
    deviceGroupId: {
      required: false,
      type: Number,
      default: 0
    },
    deptId:{
      required: false,
      type: Number,
      default: 0
    }
  }
);

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

// I18n
const { t } = useI18n();

// 本地响应式状态管理对话框可见性
const dialogVisible = ref(props.visible);

// 表单数据
const formData = reactive({
  deptId: null as number | null,
  sceneIds: [] as number[]
});

// 场景列表
const sceneList = ref<any[]>([]);
// 加载状态
const loading = reactive({
  scenes: false,
  submit: false
});

// 使用逻辑钩子获取部门数据
const {deptTreeList, getDeptTree} = useLogic();



// 加载分组已绑定的场景
const loadGroupScenes = async () => {
  if (!props.deviceGroupId) return;

  loading.scenes = true;
  try {
    const res = await getSceneListByDeviceGroupApi(props.deviceGroupId);
    if (res.code === 0 && res.data?.scenes) {
      formData.sceneIds = res.data.scenes.map((scene: any) => scene.id);
    }
  } catch (error) {
    console.error('Failed to load device group scenes:', error);
  } finally {
    loading.scenes = false;
  }
};

// 加载场景列表
const loadSceneList = async () => {
  if (!formData.deptId) {
    sceneList.value = [];
    return;
  }

  loading.scenes = true;
  try {
    const res = await getAlertSceneOptionsApi({
      deptId: formData.deptId,
    });
    if(res.code === 0 && res.data) {
      sceneList.value = res.data.options ? res.data.options :[];
    }else{
      sceneList.value = []
    }
  } catch (error) {
    console.error('Failed to load scene list:', error);
    sceneList.value = [];
  } finally {
    loading.scenes = false;
  }
};
// 处理部门变更
watch(() => props.deptId, (newDeptId) => {
  if (newDeptId && newDeptId>0) {
    formData.deptId = newDeptId;
  }
});
// 处理部门变更
watch(() => formData.deptId, (newDeptId) => {
  if (newDeptId) {
    loadSceneList();
  }
});

// 处理确定按钮
const handleConfirm = async () => {
  if (!props.deviceGroupId) {
    ElMessage.warning(t('alerts.sceneOperatePage.selectDeptFirst'));
    return;
  }

  loading.submit = true;
  try {
    const res = await setDeviceGroupSceneRelApi(props.deviceGroupId, formData.sceneIds);
    if (res.code === 0) {
      ElMessage.success(t('alerts.sceneOperatePage.bindSuccess'));
      emit('success');
      handleClose();
    } else {
      ElMessage.error(res.msg || t('alerts.sceneOperatePage.bindFailed'));
    }
  } catch (error) {
    console.error('Failed to bind scenes:', error);
    ElMessage.error(t('alerts.sceneOperatePage.bindFailed'));
  } finally {
    loading.submit = false;
  }
};

// 处理关闭
const handleClose = () => {
  // 重置表单数据
  // formData.deptId = null;
  // formData.sceneIds = [];
  // sceneList.value = [];
  emit('update:visible', false);
};

// 监听props.visible变化，更新本地状态
watch(() => props.visible, (newVisible) => {
  dialogVisible.value = newVisible;
}, { immediate: true });

// 监听visible变化，加载数据
watch(() => props.visible, async (newVisible) => {
  if (newVisible) {
    // 重置表单
    formData.sceneIds = [];
    // 加载数据
    await getDeptTree();
    await loadGroupScenes();
  }
});

// 组件挂载时
onMounted(async () => {
  if (props.visible) {
    await getDeptTree();
    await loadGroupScenes();
  }
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('alerts.sceneOperatePage.sceneSection')"
    width="600px"
    @close="handleClose"
  >
    <el-form label-width="100px">
      <el-form-item :label="t('alerts.sceneOperatePage.deptId')">
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
            value: 'id',
            label: 'name',
            emitPath: false,
            checkStrictly: true
          }"

          clearable
          filterable
          :placeholder="t('alerts.sceneOperatePage.deptId')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children?.length || 0 }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item :label="t('alerts.sceneOperatePage.sceneSection')">
        <el-select
          v-model="formData.sceneIds"
          multiple
          collapse-tags
          class="w-full"
          :loading="loading.scenes"
          :placeholder="t('alerts.sceneOperatePage.sceneSection')"
        >
          <el-option
            v-for="(scene,index) in sceneList"
            :key="index"
            :label="scene.label"
            :value="scene.val"
          />
        </el-select>
        <div class="mt-2 text-gray-500 text-sm" v-if="formData.sceneIds.length > 0">
          {{ t('alerts.sceneOperatePage.selectedCount', { count: formData.sceneIds.length }) }}
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">{{ t('alerts.sceneOperatePage.cancelButton') }}</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading.submit">
        {{ t('alerts.sceneOperatePage.confirmButton') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
}
</style>
